"use strict";

const { Controller } = require("egg");

class HomeController extends Controller {
	async index() {
		const { ctx } = this;
		console.log("ctx.query:", ctx.query);
		const { id } = ctx.query;
		ctx.body = id;
	}

	// 获取用户信息
	async user() {
		const { ctx } = this;
		const { id } = ctx.params;
		console.log("ctx.params:", ctx.params);
		ctx.body = id;
	}

	// 添加标题
	async add() {
		const { ctx } = this;
		const { title } = ctx.request.body;
		// Egg框架内置了bodyParser中间件来对POST请求body解析成 object 挂载到 ctx.request.body 上
		console.log("ctx.request.body:", ctx.request.body);
		ctx.body = {
			title,
		};
	}

	/* 
  从这里开始连接数据库里的数据
  查询接口
  
  */
	async getuser() {
		const { ctx } = this;
		const result = await ctx.service.home.getuser();
		ctx.body = result;
	}

	/* 
  新增接口
  */
	async addUser() {
		const { ctx } = this;
		const { name } = ctx.request.body;
		// 先获取输入的name
		try {
			const result = await ctx.service.home.addUser(name);
			ctx.body = {
				code: 200,
				msg: "添加成功",
				data: null,
			};
		} catch (error) {
			ctx.body = {
				code: 500,
				msg: "添加失败",
				data: null,
			};
		}
	}

	/* 
  编辑接口
  */
	async editUser() {
		const { ctx } = this;
		const { id, name } = ctx.request.body;
		try {
			const result = await ctx.service.home.editUser(id, name);
			ctx.body = {
				code: 200,
				msg: "修改成功",
				data: null,
			};
			return result;
		} catch (error) {
			ctx.body = {
				code: 500,
				msg: "修改失败",
				data: null,
			};
		}
	}

	/* 
  删除接口
  */
	async deleteUser() {
		const { ctx } = this;
		const { id } = ctx.request.body;

		try {
			const result = await ctx.service.home.deleteUser(id);
			ctx.body = {
				code: 200,
				msg: "删除成功",
				data: null,
			};
			return result;
		} catch (error) {
			console.log(error);
			ctx.body = {
				code: 500,
				msg: "删除失败",
				data: null,
			};
		}
	}
}

module.exports = HomeController;
